layui.define(['table', 'layerPlus'], function(exports) {
  var layer = layui.layerPlus
    , $ = layui.jquery
    , table = layui.table
    , localData = layui.data('local')
    , detailTables = {};

  var defaultConfig = {
    target: '',// 绑定的div
    title: '', // 标题
    cols: [[]],//表格列
    response: {
      statusCode: 200 //重新规定成功的状态码为 200，table 组件默认为 0
      , countName: 'total' //规定数据总数的字段名称，默认：count
      , dataName: 'data' //规定数据列表的字段名称，默认：data
    },
    request: {
      pageName: 'page',
      limitName: 'limit'
    },
    headers: {
      'token': localData.token
    },
    tempRow: {},// 添加新行的默认值
    cellMinWidth: 100,
    defaultToolbar: [],
    barEvent: {
      'del': function(obj) {
        layer.confirmWindow('真的删除行么', function(index) {
          obj.del();
          layer.close(index);
        });
      }
    },
    toolEvent: {
      'add': function(data, tableId, _config) {
        var oldData = table.cache[tableId];
        oldData.push(_config.tempRow);
        table.reload(tableId, {
          data: oldData
        });
      }
    },
    dbClick: null,
    limit: 1000,
    toolbar: '<div><a class="layui-btn layui-btn-sm" lay-event="add">添加</a></div>'
  };

  var ksDetails = {
    config: {},
    getData: function(id) {
      var rows = table.cache[id]
        , rtn = [];
      layui.each(rows, function(index, row) {
        var data = {}
          , flag = false;
        layui.each(row, function(i, d) {
          if(i !== 'LAY_TABLE_INDEX') {
            data[i] = d;
            flag = true;
          }
        });
        if(flag) rtn.push(data);
      });
      return rtn;
    },
    setData: function(id, data) {
      table.reload(id, {data: data})
    },
    render: function(properties) {
      this.config = $.extend(true, {}, defaultConfig, properties);
      var _config = this.config
        , target = _config.target;
      if(!target || $(target)[0].tagName.toLowerCase() !== 'div' || $(target).length > 1) {
        layer.msg.warn('每次只能绑定单个div元素');
        return;
      }
      var id = _config.id || 'detailTable_' + Object.keys(detailTables).length + 1
        , tableId = id
        , html = [
        '<fieldset class="layui-elem-field layui-field-title">',
        '  <legend>' + (_config.title || '') + '</legend>',
        '  <table id="' + id + '" class="layui-hide" lay-filter="' + id + '"></table>',
        '</fieldset>'
      ];
      $(target).replaceWith(html.join(''));
      var tableConfig = {
        id: tableId,
        elem: '#' + tableId,
        cols: _config.cols,
      };
      tableConfig = $.extend(true, tableConfig, _config);

      if(_config.url) {// 初始化远程数据
        var ajaxConfig = {
          loading: true,
          autoSort: false,
          response: _config.response,
          request: _config.request,
          headers: _config.headers,
          where: _config.where,
        };
        tableConfig = $.extend(true, {}, tableConfig, ajaxConfig);
      }
      detailTables[tableId] = table.render(tableConfig);
      //行工具栏事件
      table.on('tool(' + tableId + ')', function(obj) {
        var fun = _config.barEvent[obj.event];
        if(fun && typeof fun === 'function') {
          _config.barEvent[obj.event](obj, _config);
        } else {
          layer.msg.error('未定义对应事件');
        }
      });
      //监听头工具事件
      table.on('toolbar(' + tableId + ')', function(obj) {
        var checkStatus = table.checkStatus(obj.config.id)
          , _event = obj.event
          , data = checkStatus.data;
        var fun = _config.toolEvent[_event];
        if(fun && typeof fun === 'function') {
          _config.toolEvent[obj.event](data, tableId, _config);
        } else {
          layer.msg.error('未定义对应事件');
        }
      });

      if(typeof _config.dbClick === 'function') {
        //监听行双击事件
        table.on('rowDouble(' + tableId + ')', function(obj) {
          _config.dbClick(obj);
        });
      }

      return detailTables[tableId];
    }
  };

  exports('ksDetails', ksDetails)
});
